#include "statements.h"
#include "../Dict.h"
#include "../file_manager.h"
#include "../IdxMgr.h"
#include "../page.h"
#include "../Logger.h"
#include <iostream>
#include <sstream>
#include <chrono>
#include <thread>
#include <iomanip>
#include <algorithm>

using namespace std;

namespace ment {

	// 静态成员初始化
	SQLStatementConfig SQLStatementManager::globalConfig_;
	std::unique_ptr<DefaultSQLStatementProcessor> SQLStatementManager::defaultProcessor_;

	// ========== SQLStatementContext 实现 ==========
	SQLStatementContext::SQLStatementContext() {
		reset();
	}

	//9.12
	static string checkStatType(StatType statType, Stat* val, const char* colName, int line, int column);

	//9.12.1
	// 递归检查 WHERE 里所有“列 op 值”节点
	static std::string checkWhereColType(Stat* e, Dict* dict, Class* cls,
		const std::vector<Attribute*>& attrs,
		int line, int column) {
		if (!e) return "";
		if (e->type == kStatOperator &&
			e->opType >= kOpEquals && e->opType <= kOpGreaterEq) {
			if (e->stat && e->stat->type == kStatColumnRef &&
				e->stat2 && e->stat2->isLiteral() &&
				e->stat2->type != kStatLiteralNull) {
				Attribute* col = dict->findColumn(cls, attrs, e->stat->name);
				if (!col) return "";
				return checkStatType(col->type, e->stat2, col->name.c_str(),
					line, column);  // 使用传入的 line 和 column
			}
		}
		// 递归子树
		if (e->stat) {
			auto l = checkWhereColType(e->stat, dict, cls, attrs, line, column);
			if (!l.empty()) return l;
		}
		if (e->stat2) {
			auto r = checkWhereColType(e->stat2, dict, cls, attrs, line, column);
			if (!r.empty()) return r;
		}
		return "";
	}


	SQLStatementContext::~SQLStatementContext() = default;

	void SQLStatementContext::setConfig(const SQLStatementConfig& config) {
		config_ = config;
	}

	const SQLStatementConfig& SQLStatementContext::getConfig() const {
		return config_;
	}

	void SQLStatementContext::setCurrentUser(const std::string& username) {
		currentUser_ = username;
	}

	const std::string& SQLStatementContext::getCurrentUser() const {
		return currentUser_;
	}

	void SQLStatementContext::setCurrentSchema(const std::string& schema) {
		currentSchema_ = schema;
	}

	const std::string& SQLStatementContext::getCurrentSchema() const {
		return currentSchema_.empty() ? config_.defaultSchema : currentSchema_;
	}

	void SQLStatementContext::addExecutionLog(const std::string& log) {
		if (config_.enableLogging) {
			auto now = std::chrono::system_clock::now();
			auto time_t = std::chrono::system_clock::to_time_t(now);
			std::stringstream ss;
			ss << "[" << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S") << "] " << log;
			executionLogs_.push_back(ss.str());
		}
	}

	const std::vector<std::string>& SQLStatementContext::getExecutionLogs() const {
		return executionLogs_;
	}

	void SQLStatementContext::reset() {
		currentUser_.clear();
		currentSchema_.clear();
		executionLogs_.clear();
	}

	// ========== SQLStatementValidator 实现 ==========
	SQLStatementValidator::SQLStatementValidator(SQLStatementContext* context)
		: context_(context) {
	}

	bool SQLStatementValidator::validateStatement(SQLStatement* statement) {
		if (!statement) {
			validationErrors_.push_back("SQL statement is empty, please provide a valid SQL statement");
			return false;
		}

		bool syntaxValid = validateSyntax(statement);
		bool semanticsValid = validateSemantics(statement);
		bool permissionsValid = validatePermissions(statement, context_->getCurrentUser());

		return syntaxValid && semanticsValid && permissionsValid;
	}

	bool SQLStatementValidator::validateSyntax(SQLStatement* statement) {
		// 基本语法验证
		if (!statement) {
			validationErrors_.push_back("SQL statement syntax is invalid, please check the statement format");
			return false;
		}
		return true;
	}

	bool SQLStatementValidator::validateSemantics(SQLStatement* statement) {
		// 语义验证
		return true;
	}

	bool SQLStatementValidator::validatePermissions(SQLStatement* statement, const std::string& username) {
		// 权限验证
		if (username.empty()) {
			validationErrors_.push_back("User authentication failed, please login first");
			return false;
		}
		return true;
	}

	const std::vector<std::string>& SQLStatementValidator::getValidationErrors() const {
		return validationErrors_;
	}

	void SQLStatementValidator::clearErrors() {
		validationErrors_.clear();
	}

	// ========== SQLStatementProcessor 实现 ==========
	SQLStatementProcessor::SQLStatementProcessor(SQLStatementContext* context)
		: context_(context) {
		validator_ = std::make_unique<SQLStatementValidator>(context);
	}

	std::string SQLStatementProcessor::processStatement(SQLStatement* statement, const std::string& username) {
		context_->setCurrentUser(username);
		context_->addExecutionLog("Processing SQL statement");

		// 预处理
		if (preProcessor_) {
			preProcessor_(statement);
		}

		// 验证
		if (context_->getConfig().enableValidation) {
			if (!validator_->validateStatement(statement)) {
				std::string errorMsg = "Validation failed: ";
				for (const auto& error : validator_->getValidationErrors()) {
					errorMsg += error + "; ";
				}
				return errorMsg;
			}
		}

		// 执行原始语句
		std::string result = statement->execute(username);

		// 后处理
		if (postProcessor_) {
			postProcessor_(statement, result);
		}

		context_->addExecutionLog("Statement execution completed");
		return result;
	}

	void SQLStatementProcessor::setPreProcessor(std::function<void(SQLStatement*)> processor) {
		preProcessor_ = processor;
	}

	void SQLStatementProcessor::setPostProcessor(std::function<void(SQLStatement*, const std::string&)> processor) {
		postProcessor_ = processor;
	}

	// ========== SQLExecutionEngine 实现 ==========
	SQLExecutionEngine::SQLExecutionEngine(const SQLStatementConfig& config) {
		context_ = std::make_unique<SQLStatementContext>();
		context_->setConfig(config);
		processor_ = std::make_unique<SQLStatementProcessor>(context_.get());
	}

	SQLExecutionEngine::~SQLExecutionEngine() = default;

	std::string SQLExecutionEngine::executeStatement(SQLStatement* statement, const std::string& username) {
		auto start = std::chrono::high_resolution_clock::now();

		std::string result = processor_->processStatement(statement, username);

		auto end = std::chrono::high_resolution_clock::now();
		auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

		if (duration.count() > context_->getConfig().maxExecutionTime) {
			context_->addExecutionLog("Warning: Statement execution exceeded timeout");
		}

		return result;
	}

	void SQLExecutionEngine::setExecutionTimeout(int timeoutMs) {
		SQLStatementConfig config = context_->getConfig();
		config.maxExecutionTime = timeoutMs;
		context_->setConfig(config);
	}

	void SQLExecutionEngine::enableQueryOptimization(bool enable) {
		SQLStatementConfig config = context_->getConfig();
		config.enableOptimization = enable;
		context_->setConfig(config);
	}

	const SQLStatementContext& SQLExecutionEngine::getContext() const {
		return *context_;
	}

	// ========== SQLStatementFactory 实现 ==========
	SQLStatementFactory& SQLStatementFactory::getInstance() {
		static SQLStatementFactory instance;
		return instance;
	}

	std::unique_ptr<ISQLStatementProcessor> SQLStatementFactory::createProcessor(const SQLStatementConfig& config) {
		return std::make_unique<DefaultSQLStatementProcessor>(config);
	}

	std::unique_ptr<SQLExecutionEngine> SQLStatementFactory::createExecutionEngine(const SQLStatementConfig& config) {
		return std::make_unique<SQLExecutionEngine>(config);
	}

	void SQLStatementFactory::registerStatementType(StatementType type, std::function<std::unique_ptr<SQLStatement>()> factory) {
		statementFactories_[type] = factory;
	}

	std::unique_ptr<SQLStatement> SQLStatementFactory::createStatement(StatementType type) {
		auto it = statementFactories_.find(type);
		if (it != statementFactories_.end()) {
			return it->second();
		}
		return nullptr;
	}

	// ========== DefaultSQLStatementProcessor 实现 ==========
	DefaultSQLStatementProcessor::DefaultSQLStatementProcessor(const SQLStatementConfig& config) {
		context_ = std::make_unique<SQLStatementContext>();
		context_->setConfig(config);
		processor_ = std::make_unique<SQLStatementProcessor>(context_.get());
	}

	DefaultSQLStatementProcessor::~DefaultSQLStatementProcessor() = default;

	std::string DefaultSQLStatementProcessor::execute(const std::string& username, SQLStatement* statement) {
		return processor_->processStatement(statement, username);
	}

	bool DefaultSQLStatementProcessor::validate(SQLStatement* statement) {
		SQLStatementValidator validator(context_.get());
		return validator.validateStatement(statement);
	}

	void DefaultSQLStatementProcessor::optimize(SQLStatement* statement) {
		// 优化逻辑可以在这里实现
		if (context_->getConfig().enableOptimization) {
			context_->addExecutionLog("Statement optimization applied");
		}
	}

	// ========== SQLStatementManager 实现 ==========
	std::string SQLStatementManager::executeStatement(SQLStatement* statement, const std::string& username) {
		if (!defaultProcessor_) {
			defaultProcessor_ = std::make_unique<DefaultSQLStatementProcessor>(globalConfig_);
		}
		return defaultProcessor_->execute(username, statement);
	}

	bool SQLStatementManager::validateStatement(SQLStatement* statement) {
		if (!defaultProcessor_) {
			defaultProcessor_ = std::make_unique<DefaultSQLStatementProcessor>(globalConfig_);
		}
		return defaultProcessor_->validate(statement);
	}

	std::unique_ptr<ISQLStatementProcessor> SQLStatementManager::createProcessor(const SQLStatementConfig& config) {
		return SQLStatementFactory::getInstance().createProcessor(config);
	}

	std::unique_ptr<SQLExecutionEngine> SQLStatementManager::createEngine(const SQLStatementConfig& config) {
		return SQLStatementFactory::getInstance().createExecutionEngine(config);
	}

	void SQLStatementManager::setGlobalConfig(const SQLStatementConfig& config) {
		globalConfig_ = config;
		defaultProcessor_.reset(); // 重置以使用新配置
	}

	const SQLStatementConfig& SQLStatementManager::getGlobalConfig() {
		return globalConfig_;
	}

	//9.11 语义分析
	std::string checkStatCols(Stat* e, Dict* dict, Class* cls, const std::vector<Attribute*>& attrs);

	std::vector<Stat*> select(std::vector<Stat*> ori, Stat* whereClause, std::vector<Attribute*> attrs);
	std::vector<Stat*> project(std::vector<Stat*> ori, std::vector<Stat*> selectList, std::vector<Attribute*> attrs);
	std::vector<Stat*> intersectStats(std::vector<Stat*> left, std::vector<Stat*> right);
	std::vector<Stat*> unionStats(std::vector<Stat*> left, std::vector<Stat*> right);



	//9.12 类型转换
	// 把 StatType 转成人类可读字符串
	static const char* statTypeName(StatType t) {
		switch (t) {
		case kStatLiteralInt:    return "INT";
		case kStatLiteralFloat:  return "FLOAT";
		case kStatLiteralString: return "STRING";
		case kStatLiteralNull:   return "NULL";
		case kStatLiteralBool:   return "BOOL";
		default:                 return "UNKNOWN";
		}
	}

	// ColumnDefinition 
	ColumnDefinition::ColumnDefinition(char* name, ColumnType type, bool nullable) :name(name), type(type), nullable(nullable) {};

	ColumnDefinition::~ColumnDefinition() {
		free(name);
	}

	//ColumnType::ColumnType(DataType data_type, int64_t length) :data_type(data_type), length(length) {};
	//9.14.3
	ColumnType::ColumnType(DataType data_type, int64_t length)
		: data_type(data_type), length(length) {
	};  // 确保这里正确初始化

	//9.12.1
	// 仅判断“表达式是否属于布尔类别”，不递归子树
	static bool isBooleanContext(Stat* e) {
		if (!e) return false;
		switch (e->type) {
		case kStatLiteralBool:          // 字面量 true/false
			return true;
		case kStatOperator:
			// 所有比较、逻辑运算都返回布尔
			switch (e->opType) {
			case kOpEquals: case kOpNotEquals:
			case kOpLess: case kOpLessEq:
			case kOpGreater: case kOpGreaterEq:
			case kOpLike: case kOpNotLike: case kOpILike:
			case kOpAnd: case kOpOr: case kOpNot:
			case kOpIn: case kOpExists:
			case kOpBetween: case kOpIsNull:
				return true;
			default:
				return false;
			}
		default:
			return false;
		}
	}

	bool operator==(const ColumnType& lhs, const ColumnType& rhs) {
		if (lhs.data_type != rhs.data_type) return false;
		if (lhs.data_type == DataType::VARCHAR || lhs.data_type == DataType::CHAR) {
			return lhs.length == rhs.length;
		}
		return true;
	}

	bool operator!=(const ColumnType& lhs, const ColumnType& rhs) {
		return !(lhs == rhs);
	}

	/*std::ostream& operator<<(std::ostream& stream, const ColumnType& column_type) {
		switch (column_type.data_type) {
		case DataType::UNKNOWN:
			stream << "UNKNOWN";
			break;
		case DataType::INT:
			stream << "INT";
			break;
		case DataType::LONG:
			stream << "LONG";
			break;
		case DataType::FLOAT:
			stream << "FLOAT";
			break;
		case DataType::DOUBLE:
			stream << "DOUBLE";
			break;
		case DataType::CHAR:
			stream << "CHAR(" << column_type.length << ")";
			break;
		case DataType::VARCHAR:
			stream << "VARCHAR(" << column_type.length << ")";
			break;
		case DataType::TEXT:
			stream << "TEXT";
			break;
		case DataType::BOOL:
			stream << "BOOL";
			break;
		}
		return stream;
	}*/

	//===============CreateTable算子===================
	CreateStatement::CreateStatement(CreateType type) :
		SQLStatement(ForCreate),
		type(type),
		ifNotExists(false),
		filePath(nullptr),
		schema(nullptr),
		tableName(nullptr),
		columns(nullptr),
		onWhich(nullptr),
		viewColumns(nullptr),
		select(nullptr) {
	};

	CreateStatement::~CreateStatement() {
		free(filePath);
		free(schema);
		free(tableName);
		delete select;

		if (columns != nullptr) {
			for (ColumnDefinition* def : *columns) {
				delete def;
			}
			delete columns;
		}

		if (viewColumns != nullptr) {
			for (char* column : *viewColumns) {
				free(column);
			}
			delete viewColumns;
		}
	}

	string CreateStatement::execute(string username)
	{
		Dict* dict = Dict::getInstance();
		switch (type)
		{

		case ment::ForCreateTable: {

			User* user = dict->GetUser(username);
			if (user == nullptr) {
				return "Error: User '" + username + "' does not exist or has no access permission.\n";
			}
			Database* db = dict->GetDatabase(user, schema);
			if (db == nullptr) {
				delete user;
				return "Error: Unknown database '" + string(schema) + "'. Please check if the database name is correct or if the database has been created.\n";
			}

			Class* cls = dict->CreateClass();
			cls->oid = dict->DeliverOid();
			cls->databaseid = db->GetOid();
			cls->relname = tableName;

			//文件管理
			FileManager* mgr = FileManager::getInstance();
			string fileid = mgr->allocFile();						//分配一个文件,返回文件号
			//为新表分配页
			string blockid = mgr->allocPage(fileid, PageType::table);	//在fileid中创建一个数据块. 返回块号 //这是table的BlockType类型

			//存储Class - 关系信息
			cls->relfileid = fileid;
			cls->relblockid = blockid;
			cls->relkind = 'r';									//r -> relation
			cls->relnatts = columns->size();
			dict->StoreClass(cls);



			for (int i = 0; i < columns->size(); i++) {
				//存储dict中的attribute 到dict中的attributeManager
				Attribute* attr = dict->CreateAttribute();
				attr->oid = dict->DeliverOid();
				attr->attnum = i;
				attr->name = (*columns)[i]->name;
				attr->relid = cls->oid;
				attr->notnull = (*columns)[i]->nullable;

				//9.15
// 检查是否是主键
				if ((*columns)[i]->isPrimaryKey) {
					attr->SetPkey(true);
					IdxMgr::getInstance()->createIdx(attr->oid);
					//printf("[DEBUG] Column '%s' is marked as PRIMARY KEY\n", attr->name.c_str());
				}

				if ((*columns)[i]->name == nullptr) {
					printf("[ERROR] Column name is null for column at index %d\n", i);
					continue; // 或者直接返回错误
				}


				//判断属性的类型. 并设置type
				if ((*columns)[i]->type.data_type == DataType::INT || (*columns)[i]->type.data_type == DataType::LONG) {
					attr->type = kStatLiteralInt;
				}
				else if ((*columns)[i]->type.data_type == DataType::FLOAT || (*columns)[i]->type.data_type == DataType::DOUBLE) {
					attr->type = kStatLiteralFloat;
				}
				else if ((*columns)[i]->type.data_type == DataType::VARCHAR || (*columns)[i]->type.data_type == DataType::CHAR) {
					attr->type = kStatLiteralString;
					attr->varcharlen = (*columns)[i]->type.length;
				}
				else if ((*columns)[i]->type.data_type == DataType::TEXT) {
					attr->type = kStatLiteralString;
				}
				//9.12.1
				else if ((*columns)[i]->type.data_type == DataType::BOOL) {
					attr->type = kStatLiteralBool;
				}

				// 添加调试打印
				/*printf("[DEBUG] column %s  data_type=%d  attr->type=%d\n",
					(*columns)[i]->name, (*columns)[i]->type.data_type, attr->type);*/

				dict->StoreAttribute(attr);
				delete attr;
			}
			//日志模块
			Logger::getLogger()->logToFile("Create table " + string(schema));

			delete user;
			delete db;
			delete cls;
			break;
		}//type == creat_table 

		case ment::ForCreateTableFromTbl:
			break;

		case ment::ForCreateView:
			break;

		case ment::ForCreateSchema: {
			User* user = dict->GetUser(username);
			if (user == nullptr) {
				return "Error: User '" + username + "' does not exist or has no access permission.\n";
			}

			Database* db = dict->GetDatabase(user, schema);
			if (db != nullptr)
			{
				delete user;
				delete db;
				return "Error: Cannot create database '" + string(schema) + "', the database already exists. Please use a different database name or delete the existing database and try again.\n";
			}
			db = dict->CreateDatabase();
			db->SetOwnerid(user->GetUserid());
			db->SetDatName(schema);
			db->SetOid(dict->DeliverOid());
			dict->StoreDatabase(db);

			Logger::getLogger()->logToFile("Create schema " + string(schema));
			delete user;
			delete db;
			break;
		}

		case ment::ForCreateIndex: {
			User* user = dict->GetUser(username);
			if (user == nullptr) {
				return "Error: User '" + username + "' does not exist or has no access permission.\n";
			}
			string _schema;
			if (schema == nullptr)
				if (Dict::getCurSchema() != "")
					_schema = Dict::getCurSchema();
				else {
					delete user;
					return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
				}
			else
				_schema = schema;
			Database* db = dict->GetDatabase(user, _schema);
			Class* cls = dict->GetClass(db, tableName);
			if (cls == nullptr) {
				delete user;
				delete db;
				delete cls;
				return "Error: Unknown table '" + string(tableName) + "'. Please check if the table name is correct or if the table has been created.\n";
			}
			vector<Attribute*> attrs = dict->GetAttribute(cls);
			for (auto attr : attrs) {
				if (attr->name == onWhich) {
					if (attr->IsPkey()) {
						delete user;
						delete db;
						delete cls;
						for (auto attr : attrs) {
							delete attr;
						}
						return "Error: Index on column '" + string(onWhich) + "' already exists. Only one primary key index can be created per column.\n";
					}
					else {
						attr->SetPkey(true);
						IdxMgr* mgr = IdxMgr::getInstance();
						mgr->createIdx(attr->oid);
						dict->UpdateAttribute(attr);
					}
				}
			}
			delete user;
			delete db;
			delete cls;
			for (auto attr : attrs) {
				delete attr;
			}
			//Logger::getLogger()->logToFile("Create index on " + string(schema)+"."+ string(tableName));
			break;
		}
		default:
			break;
		}

		return "";
	}


	//===============DeleteTable算子===================
	DeleteStatement::DeleteStatement() :
		SQLStatement(ForDelete),
		schema(nullptr),
		tableName(nullptr),
		stat(nullptr) {
	};

	DeleteStatement::~DeleteStatement() {
		free(schema);
		free(tableName);
		delete stat;
	}

	string DeleteStatement::execute(string username)
	{
		stringstream ss;
		Dict* dict = Dict::getInstance();
		User* user = dict->GetUser(username);
		if (user == nullptr) {
			return "Error: User '" + username + "' does not exist or has no access permission.\n";
		}
		string _schema;

		if (schema == nullptr)
			if (Dict::getCurSchema() != "")
				_schema = Dict::getCurSchema();
			else {
				delete user;
				return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
			}
		else
			_schema = schema;

		Database* db = dict->GetDatabase(user, _schema);
		Class* cls = dict->GetClass(db, tableName);

		if (cls == nullptr) {
			delete user;
			delete db;
			delete cls;
			return "Error: Unknown table '" + string(tableName) + "'. Please check if the table name is correct or if the table has been created.\n";
		}

		vector<Attribute*> attrs = dict->GetAttribute(cls);
		vector<Stat*> stats;
		vector<bool> visit;


		//9.11.4
		// 9.11 语义分析：WHERE 子句列存在性检查
		if (stat != nullptr) {
			auto err = checkStatCols(stat, dict, cls, attrs);
			if (!err.empty()) return err;
		}

		//9.12.1
		//检查 WHERE 中所有“列 op 值”是否类型匹配
		auto typeErr = checkWhereColType(stat, dict, cls, attrs, whereLine, whereColumn);
		if (!typeErr.empty()) return typeErr;

		//检查where是不是布尔上下文
		if (stat && !isBooleanContext(stat)) {
			char buf[128];
			snprintf(buf, sizeof(buf),
				"Error: WHERE clause must be a boolean expression, not a literal (line %d, column %d). Please use comparison or logical operators.",
				whereLine, whereColumn);
			return buf;
		}




		vector<string> rids;
		vector<Stat*> records;
		map<Stat*, string> recordRidMap;
		vector<bool> haveIdx;

		for (int i = 0; i < attrs.size(); i++) {
			bool hasIdx = false;
			if (attrs[i]->IsPkey()) {
				hasIdx = true;
				rids = IdxMgr::getInstance()->getRowids(attrs[i]->oid);
				records = FileManager::getInstance()->multipleGet(rids);
				for (int i = 0; i < rids.size(); i++) {
					recordRidMap[records[i]] = rids[i];
				}
			}
			haveIdx.push_back(hasIdx);
		}
		bool flag = false;
		for (auto b : haveIdx) {
			if (b == true) {
				flag = true;
			}
		}
		if (!flag) {
			////return "Error! No index";
			// 9.12.1
			//索引需求判断 /
			bool needIdx = false;
			Attribute* pkeyAttr = nullptr;  // 用于存储主键属性

			if (stat != nullptr && stat->opType == kOpEquals && stat->stat != nullptr
				&& stat->stat->type == kStatColumnRef) {
				// WHERE 主键等值 → 必须索引
				for (auto attr : attrs) {
					if (attr->IsPkey() && attr->name == stat->stat->name) {
						needIdx = true;
						pkeyAttr = attr;  // 保存主键属性
						break;
					}
				}
			}

			if (needIdx && !flag) {
				//char buf[256];
				//const char* col = stat->stat->name;                 // 主键列名
				//const char* exp = statTypeName(pkeyAttr->type);     // 预期类型
				//const char* got = statTypeName(stat->stat2->type);  // 实际类型
				//snprintf(buf, sizeof(buf),
				//	"Error: No index on primary key for equality filter (line %d, column %d): "
				//	"column '%s' expected %s, got %s",
				//	eqOpLine, eqOpColumn, col, exp, got);
				//delete user; delete db; delete cls;
				//for (auto attr : attrs) delete attr;
				//return buf;

				//9.13.3 bug修复
				bool typeMismatch = false;
				if (pkeyAttr && stat->stat2) {
					// 更合理的类型检查逻辑
					if (pkeyAttr->type == kStatLiteralInt &&
						(stat->stat2->type == kStatLiteralInt || stat->stat2->type == kStatLiteralFloat)) {
						typeMismatch = false;
					}
					else if (pkeyAttr->type == kStatLiteralFloat &&
						stat->stat2->type == kStatLiteralInt) {
						typeMismatch = false;
					}
					else {
						typeMismatch = (pkeyAttr->type != stat->stat2->type);
					}
				}

				if (typeMismatch) {
					char buf[256];
					const char* col = stat->stat->name;
					const char* exp = statTypeName(pkeyAttr->type);
					const char* got = statTypeName(stat->stat2->type);
					snprintf(buf, sizeof(buf),
						"Error: Primary key equality filter missing index (line %d, column %d): "
					"Column '%s' expects type %s, but got %s. Please check data type matching or create appropriate index",
						eqOpLine, eqOpColumn, col, exp, got);
					delete user; delete db; delete cls;
					for (auto attr : attrs) delete attr;
					return buf;
				}
				else {
					// 类型匹配但没有索引，给出警告而不是错误
					char buf[256];
					const char* col = stat->stat->name;
					snprintf(buf, sizeof(buf),
						"Warning: No index on primary key column '%s' (line %d, column %d). "
					"This may affect query performance.",
						col, eqOpLine, eqOpColumn);
					// 继续执行，不返回错误
				}
			}


		}


		vector<Stat*>res = select(records, stat, attrs);


		for (int i = 0; i < attrs.size(); i++) {
			if (attrs[i]->IsPkey()) {
				for (auto r : res) {
					IdxMgr::getInstance()->removeRecord(attrs[i]->oid, (*r->statList)[i]);
				}
			}
		}



		vector<string> tobeDeleted;
		for (auto r : res) {
			tobeDeleted.push_back(recordRidMap[r]);
		}
		FileManager::getInstance()->multipleRemove(tobeDeleted);


		//9.15
		int affectedRows = 0;
		affectedRows = tobeDeleted.size();
		stringstream sss;
		sss << "Query successful, " << affectedRows << " rows affected" << endl;
		sss << "Rows matched: " << tobeDeleted.size() << ", Changed: " << affectedRows << " rows" << endl;
		


		delete user;
		delete db;
		delete cls;
		for (auto attr : attrs) {
			delete attr;
		}
		Logger::getLogger()->logToFile("Delete from " + string(_schema) + "." + string(tableName));
		return sss.str();
	}



	//===============DropTable算子===================
	DropStatement::DropStatement(DropType type) :
		SQLStatement(ForDrop),
		type(type),
		schema(nullptr),
		name(nullptr) {
	}

	DropStatement::~DropStatement() {
		free(schema);
		free(name);
	}

	string DropStatement::execute(string username)
	{
		switch (type)
		{
		case ment::kDropTable:
			break;
		case ment::kDropSchema:
			break;
		case ment::kDropIndex:
			break;
		case ment::kDropView:
			break;
		case ment::kDropPreparedStatement:
			break;
		default:
			break;
		}
		return "";
	}


	//===============Execute算子===================
	ExecuteStatement::ExecuteStatement() :
		SQLStatement(ForExecute),
		name(nullptr),
		parameters(nullptr) {
	}

	ExecuteStatement::~ExecuteStatement() {
		free(name);

		if (parameters != nullptr) {
			for (Stat* param : *parameters) {
				delete param;
			}
			delete parameters;
		}
	}

	string ExecuteStatement::execute(string username)
	{
		return "";
	}


	//===============Import算子===================
	ImportStatement::ImportStatement(ImportType type) :
		SQLStatement(ForImport),
		type(type),
		filePath(nullptr),
		schema(nullptr),
		tableName(nullptr) {
	};

	ImportStatement::~ImportStatement() {
		free(filePath);
		free(schema);
		free(tableName);
	}

	string ImportStatement::execute(string username)
	{
		switch (type)
		{
		case ment::kImportCSV:
			break;
		case ment::kImportTbl:
			break;
		default:
			break;
		}
		return "";
	}

	//===============Insert算子===================
	InsertStatement::InsertStatement(InsertType type) :
		SQLStatement(ForInsert),
		type(type),
		schema(nullptr),
		tableName(nullptr),
		columns(nullptr),
		values(nullptr),
		select(nullptr) {
	}

	InsertStatement::~InsertStatement() {
		free(schema);
		free(tableName);
		delete select;

		if (columns != nullptr) {
			for (char* column : *columns) {
				free(column);
			}
			delete columns;
		}


		if (values != nullptr) {
			for (Stat* stat : *values) {
				delete stat;
			}
			delete values;
		}

	}

	string InsertStatement::execute(string username)
	{
		//std::cout << "[DEBUG] colPos is " << (colPos ? "not null" : "NULL") << std::endl;
		Dict* dict = Dict::getInstance();
		switch (type)
		{
		case ment::kInsertValues: {
			User* user = dict->GetUser(username);
			if (user == nullptr) {
				return "Error: User '" + username + "' does not exist. Please check if the username is correct.\n";
			}

			string _schema;
			if (schema == nullptr)
				if (Dict::getCurSchema() != "")
					_schema = Dict::getCurSchema();
				else {
					delete user;
					return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
				}
			else
				_schema = schema;

			Database* db = dict->GetDatabase(user, _schema);
			Class* cls = dict->GetClass(db, tableName);
			if (cls == nullptr) {
				delete user;
				delete db;
				return "Error: Unknown table '" + string(tableName) + "'. Please check if the table name is correct or if the table has been created.\n";
			}

			vector<Attribute*> attrs = dict->GetAttribute(cls);


			//9.13
					// 1. 先检查指定列是否存在（拦截未知列）
			if (columns) {
				for (size_t i = 0; i < columns->size(); ++i) {
					const char* colName = (*columns)[i];
					if (!dict->findColumn(cls, attrs, colName)) {
						// 用 colPos 中记录的行列号
						int line = (*colPos)[i].second.first;
						int col = (*colPos)[i].second.second;
						return "Error: Attribute '" + std::string(colName) +
				"' does not exist (line " + std::to_string(line) +
				", column " + std::to_string(col) + ")";

					}
				}
				// 值少了
				if (values->size() < columns->size()) {
					return "Error: Attribute and value mismatch (missing value for attribute '" +
				std::string((*columns)[values->size()]) +
				"' (line " + std::to_string(valuesLine) +
				", column " + std::to_string(valuesColumn) + "))";
				}
				// 值多了
				if (values->size() > columns->size()) {


					// 2.a 先找“剩余列”里有没有 notnull
					std::vector<Attribute*> missingAttrs;
					for (auto attr : attrs) {
						bool inList = false;
						for (size_t j = 0; j < columns->size(); ++j)
							if (strcmp(attr->name.c_str(), (*columns)[j]) == 0) { inList = true; break; }
						if (!inList) missingAttrs.push_back(attr);
					}
					for (auto m : missingAttrs)
					if (m->notnull)
						return "Error: Attribute and value mismatch (missing value for non-null attribute '" + m->name + "' ...)";

					// 2.b 剩余全 nullable → 才是真多余
					Stat* firstExtra = (*values)[columns->size()];
					return "Error: Attribute and value mismatch (extra value at line " +
					std::to_string(firstExtra->first_line) +
					", column " + std::to_string(firstExtra->first_column) + ")";

				}
			}
			else {
				// 全列插入：值少了
				if (values->size() < attrs.size()) {
					// 先判断剩余列是否全部 nullable
					bool allNullable = true;
					for (size_t i = values->size(); i < attrs.size(); ++i) {
						if (attrs[i]->notnull) {
							allNullable = false;
							break;
						}
					}
					if (!allNullable) {
						return "Error: Attribute and value mismatch (missing value for non-null attribute '" +
						attrs[values->size()]->name +
						"' at line " + std::to_string(valuesLine) +
						", column " + std::to_string(valuesColumn) + ")";
					}
				}
				// 值多了
				if (values->size() > attrs.size()) {
					Stat* firstExtra = (*values)[attrs.size()];
					return "Error: Attribute and value mismatch (extra value at line " +
					std::to_string(firstExtra->first_line) +
					", column " + std::to_string(firstExtra->first_column) + ")";
				}
			}

			// 2. 再检查值数量
			if (columns && values) {

				if (columns->size() != values->size()) {
					//std::cout << "[DEBUG] 列值数量不匹配检查" << std::endl;
					// 找到出错的第一个不匹配项
					size_t minSize = (std::min)(columns->size(), values->size());
					size_t errorIndex = minSize;   // 第一个多出来的项下标

					std::stringstream msg;
					msg << "Error: Attribute and value mismatch";

					if (errorIndex < columns->size()) {
						//std::cout << "[DEBUG] 列多出来了" << std::endl;
						// 列多出来了
						if (colPos && errorIndex < colPos->size()) {
							auto& pos = (*colPos)[errorIndex];
							errorLine = pos.second.first;
							errorColumn = pos.second.second;
							msg << " (missing value for attribute '" << (*columns)[errorIndex] << "' at line "
					<< errorLine << ", column " << errorColumn << ")";
						}
						else {
							//  Fallback：用列列表起始位置
							errorLine = errorLine;   // 外部已设
							errorColumn = errorColumn; // 外部已设
							msg << " (missing value for column '" << "')";
						}
					}
					else if (errorIndex < values->size()) {
						//std::cout << "[DEBUG] 值多出来了，开始判断是“缺非空列”还是“多余值”" << std::endl;

						std::vector<Attribute*> missingAttrs;

						for (auto attr : attrs) {
							bool found = false;
							for (size_t i = 0; i < columns->size(); ++i) {
								if (strcmp(attr->name.c_str(), (*columns)[i]) == 0) {
									found = true;
									break;
								}
							}
							if (!found) missingAttrs.push_back(attr);
						}

						// 只要有一个非空列缺失 → 报“缺非空列”
						for (auto missed : missingAttrs) {
							if (missed->notnull) {
								return "Error: Missing value for non-null attribute '" +
						attrs[errorIndex]->name +
						"' at line " + std::to_string(valuesLine) +
						", column " + std::to_string(valuesColumn) + ")";
							}
						}

						// 否则才报“多余值”
						Stat* firstExtra = (*values)[columns->size()];
						return "Error: Extra value at line " +
					std::to_string(firstExtra->first_line) +
					", column " + std::to_string(firstExtra->first_column) + ")";
					}

					return msg.str();
				}
			}

			if (!values) {
				//std::cout << "[DEBUG] values 指针为空" << std::endl;
				delete user; delete db; delete cls;
				for (auto a : attrs) delete a;
				return "Error: No values provided for INSERT statement";
			}


			//std::cout << "[DEBUG] values 大小: " << values->size() << std::endl;


			//9.13.5
		// 全列插入检查
			if (!columns) {
				if (values->size() < attrs.size()) {
					// 值少了 - 使用VALUES子句的位置
					int line = valuesLine > 0 ? valuesLine : 1;
					int col = valuesColumn > 0 ? valuesColumn : 1;

					std::stringstream msg;
					msg << "Error: Attribute and value mismatch (expected "
					<< attrs.size() << " values, got " << values->size() << ")"
					<< " (line " << line << ", column " << col
					<< " - missing value for attribute '" << attrs[values->size()]->name << "')";

					return msg.str();
				}
				else if (values->size() > attrs.size()) {
					// 值多了 - 使用第一个多余值的位置
					int line = 1;
					int col = 1;

					if (values->size() > attrs.size() && (*values)[attrs.size()]) {
						line = (*values)[attrs.size()]->first_line;
						col = (*values)[attrs.size()]->first_column;
					}

					std::stringstream msg;
					msg << "Error: Column count and value count mismatch (expected "
					<< attrs.size() << " values, got " << values->size() << ")"
					<< " (line " << line << ", column " << col
					<< " - extra values)";

					return msg.str();
				}
			}


			//std::cout << "[DEBUG] 准备处理值" << std::endl;
			vector<Stat*> stats;
			vector<bool> visit;

			/* ===== 带列名插入: INSERT INTO t(a,b) VALUES (...) ===== */
			if (columns != nullptr) {
				//std::cout << "[DEBUG] 处理带列名插入" << std::endl;
				for (auto attr : attrs) {
					bool found = false;
					for (size_t i = 0; i < columns->size(); ++i) {
						if (strcmp(attr->name.c_str(), (*columns)[i]) == 0) {
							//std::cout << "[DEBUG] 处理列: " << attr->name << std::endl;
							/* 类型检查 */

							//9.14.6 varchar长度检查
							/* ===== 在这里加检查 ===== */
							if (attr->type == kStatLiteralString && (*values)[i]->type == kStatLiteralString) {
								int maxLen = attr->varcharlen;
								int actualLen = strlen((*values)[i]->name);
								if (actualLen > maxLen) {
									char buf[512];
									snprintf(buf, sizeof(buf),
										"Error: Attribute '%s' length exceeds limit (line %d, column %d): max length %d, actual length %d",
										attr->name.c_str(),
										(*values)[i]->first_line, (*values)[i]->first_column,
										maxLen, actualLen);
									delete user; delete db; delete cls;
									for (auto a : attrs) delete a;
									return buf;
								}
							}
							/* ====================== */


							string err = checkStatType(attr->type, (*values)[i], attr->name.c_str(), errorLine, errorColumn);
							if (!err.empty()) {
								delete user; delete db; delete cls;
								for (auto a : attrs) delete a;
								return err;
							}

							/* 构造 stat */
							if (attr->type == kStatLiteralString)
								stats.push_back(Stat::makeLiteral(string((*values)[i]->name).substr(0, attr->varcharlen).c_str()));
							else
								stats.push_back((*values)[i]);
							found = true;
							break;
						}
					}
					visit.push_back(found);
					if (!found) {
						if (attr->IsNotNull()) {
							delete user; delete db; delete cls;
							for (auto a : attrs) delete a;
							return "Error: Attribute " + attr->name + " cannot be null\n";
						}
						else {
							stats.push_back(Stat::makeNullLiteral());
						}
					}
				}
			}

			/* ===== 全列插入: INSERT INTO t VALUES (...) ===== */
			else {
				//std::cout << "[DEBUG] 处理全列插入" << std::endl;

				// 创建 values 的本地副本以确保安全
				std::vector<Stat*> localValues;
				for (size_t i = 0; i < values->size(); i++) {
					if ((*values)[i] && reinterpret_cast<uintptr_t>((*values)[i]) > 0x1000) {
						localValues.push_back((*values)[i]);
					}
					else {
						//std::cout << "[DEBUG] 跳过无效值指针: " << (*values)[i] << std::endl;
						localValues.push_back(Stat::makeNullLiteral());
					}
				}

				for (size_t i = 0; i < attrs.size(); ++i) {
					//std::cout << "[DEBUG] 处理第 " << i << " 个值" << std::endl;

					if (i >= localValues.size()) {
						//std::cout << "[DEBUG] 错误：值索引越界" << std::endl;
						delete user; delete db; delete cls;
						for (auto a : attrs) delete a;
						return "Error: Internal error - value index out of bounds";
					}

					Stat* currentValue = localValues[i];
					//std::cout << "[DEBUG] 值指针: " << currentValue << ", 类型: " << currentValue->type << std::endl;

					//9.14.6 varchar长度检查
					/* ===== 在这里加检查 ===== */
					if (attrs[i]->type == kStatLiteralString && currentValue->type == kStatLiteralString) {
						int maxLen = attrs[i]->varcharlen;
						int actualLen = strlen(currentValue->name);
						if (actualLen > maxLen) {
							char buf[512];
							snprintf(buf, sizeof(buf),
								"Error: Column '%s' length exceeds limit (line %d, column %d): max length %d, actual length %d",
								attrs[i]->name.c_str(),
								currentValue->first_line, currentValue->first_column,
								maxLen, actualLen);
							delete user; delete db; delete cls;
							for (auto a : attrs) delete a;
							return buf;
						}
					}
					/* ====================== */


					visit.push_back(true);

					/* /类型检查 - 使用安全的错误位置 */
					int errorLineForValue = (currentValue->first_line > 0) ? currentValue->first_line : 1;
					int errorColumnForValue = (currentValue->first_column > 0) ? currentValue->first_column : 22;

					//9.11.4
					//string err = checkStatType(attrs[i]->type, currentValue, attrs[i]->name.c_str(),
						//errorLineForValue, errorColumnForValue);
					string err = checkStatType(attrs[i]->type,
						currentValue,
						attrs[i]->name.c_str(),
						currentValue->first_line,   // ← 用值的
						currentValue->first_column);
					if (!err.empty()) {
						delete user; delete db; delete cls;
						for (auto a : attrs) delete a;
						return err;
					}


					/* ✅ 构造 stat */
					if (attrs[i]->type == kStatLiteralString) {
						if (currentValue->type == kStatLiteralNull) {              // ← 新增
							stats.push_back(Stat::makeNullLiteral());
						}
						else if (currentValue->name && reinterpret_cast<uintptr_t>(currentValue->name) > 0x1000) {
							stats.push_back(Stat::makeLiteral(string(currentValue->name).substr(0, attrs[i]->varcharlen).c_str()));
						}
						else {
							stats.push_back(Stat::makeLiteral(""));
						}
					}
					else if (attrs[i]->type == kStatLiteralFloat && currentValue->type == kStatLiteralInt) {
						stats.push_back(Stat::makeLiteral((double)currentValue->ival));
					}
					else {
						stats.push_back(currentValue);
					}
				}
			}

			//9.15
			/* ===== 主键唯一性检查 ===== */
			for (size_t i = 0; i < attrs.size(); ++i) {
				if (attrs[i]->IsPkey()) {
					auto existing = IdxMgr::getInstance()->getRowids(attrs[i]->oid, stats[i], EQ);
					if (!existing.empty()) {
						char buf[512];
						snprintf(buf, sizeof(buf),
							"Error: Duplicate primary key value, cannot insert (line %d, column %d): value for column '%s' already exists",
							stats[i]->first_line, stats[i]->first_column, attrs[i]->name.c_str());
						delete user; delete db; delete cls;
						for (auto a : attrs) delete a;
						return buf;
					}
				}
			}


			for (size_t i = 0; i < values->size(); ++i) {
				printf("[INSERT] col=%zu  type=%d  ival=%lld\n",
					i, (*values)[i]->type, (*values)[i]->ival);
			}


			/* ===== 写入数据 ===== */
			Page* blk = FileManager::getInstance()->getLastAvailablePage(cls->relfileid);
			if (blk == nullptr) {
				// 修复：处理getLastAvailablePage返回空指针的情况
				delete user; delete db; delete cls;
				for (auto attr : attrs) delete attr;
				return "Error: Cannot get available page for insert operation. Possible insufficient storage space or file system error, please check disk space.\n";
			}


			Stat* final = Stat::makeArray(&stats);

			string rid = blk->put(final);

			for (size_t i = 0; i < attrs.size(); ++i) {
				if (visit[i] && attrs[i]->IsPkey()) {
					IdxMgr::getInstance()->addRecord(attrs[i]->oid, stats[i], rid);
				}
			}



			//9.15
			 // 在执行插入后添加
			int affectedRows = 1;
			stringstream sss;
			sss << "Insert successful, " << affectedRows << " rows affected" << endl;
			sss << "Changed: " << affectedRows << " rows" << endl;
			return sss.str();
			return sss.str();
			
			
			/* ===== 清理 ===== */
			delete user;
			delete db;
			delete cls;
			for (auto attr : attrs) delete attr;
			break;
		}
		case ment::kInsertSelect:
			// TODO: 类型检查留给 SELECT 子句
			break;
		default:
			break;
		}
		return "";
	}


	//===============Show算子===================
	ShowStatement::ShowStatement(ShowType type) :
		SQLStatement(ForShow),
		type(type),
		schema(nullptr),
		name(nullptr) {
	}

	ShowStatement::~ShowStatement() {
		free(schema);
		free(name);
	}

	string ShowStatement::execute(string username)
	{
		Dict* dict = Dict::getInstance();
		stringstream ss;
		switch (type)
		{
		case ment::kShowColumns: {
			if (Dict::getCurSchema() == "") {
				return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
			}
			Logger::getLogger()->logToFile("ShowStatement: About to call GetUser for " + username);
			auto user = dict->GetUser(username);
			Logger::getLogger()->logToFile("ShowStatement: GetUser returned");
			// 检查用户是否存在
			if (user == nullptr) {
				Logger::getLogger()->logToFile("ShowStatement: User is nullptr");
				return "Error: User '" + username + "' does not exist. Please check if the username is correct or contact administrator to create user.\n";
			}
			Logger::getLogger()->logToFile("ShowStatement: User found successfully");
			auto db = dict->GetDatabase(user, Dict::getCurSchema());
			auto cls = dict->GetClass(db, name);
			if (cls == nullptr) {
				delete user;
				delete db;
				return "Error: Unknown table '" + string(name) + "'. Please check if the table name is correct or if the table has been created.\n";
			}
			auto attrs = dict->GetAttribute(cls);
			for (auto attr : attrs) {
				ss << attr->name << endl;
			}
			delete user;
			delete db;
			delete cls;
			for (auto attr : attrs) {
				delete attr;
			}
			break;
		}
		case ment::kShowTables: {
			if (Dict::getCurSchema() == "") {
				return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
			}
			Logger::getLogger()->logToFile("ShowStatement(kShowTables): About to call GetUser for " + username);
			auto user = dict->GetUser(username);
			Logger::getLogger()->logToFile("ShowStatement(kShowTables): GetUser returned");
			if (user == nullptr) {
				Logger::getLogger()->logToFile("ShowStatement(kShowTables): User is nullptr");
				return "Error: User does not exist. Please check if the username is correct or contact administrator to create user.\n";
			}
			Logger::getLogger()->logToFile("ShowStatement(kShowTables): User found successfully");
			auto db = dict->GetDatabase(user, Dict::getCurSchema());
			auto clses = dict->getClasses(db);
			for (auto cls : clses) {
				ss << cls->relname << endl;
			}
			for (auto cls : clses) {
				delete cls;
			}
			break;
		}
		case ment::kShowSchemas: {
			User* user = dict->GetUser(username);
			if (user == nullptr) {
				return "Error: User does not exist. Please check if the username is correct or contact administrator to create user.\n";
			}
			auto vec = dict->getDatabases(user);
			for (auto db : vec) {
				ss << db->datname << endl;
			}
			delete user;
			for (auto v : vec) {
				delete v;
			}
			break;
		}
		default:
			break;
		}
		return ss.str();
	}


	//===============Select算子===================
	SelectStatement::SelectStatement() :
		SQLStatement(ForSelect),
		fromTable(nullptr),
		selectDistinct(false),
		selectList(nullptr),
		whereClause(nullptr),
		groupBy(nullptr),
		unionSelect(nullptr),
		order(nullptr),
		limit(nullptr) {
	};

	SelectStatement::~SelectStatement() {
		delete fromTable;
		delete whereClause;
		delete groupBy;
		delete unionSelect;
		delete limit;

		// Delete each element in the select list.
		if (selectList != nullptr) {
			for (Stat* stat : *selectList) {
				delete stat;
			}
			delete selectList;
		}

		if (order != nullptr) {
			for (OrderDescription* desc : *order) {
				delete desc;
			}
			delete order;
		}
	}

	string SelectStatement::execute(string username)
	{
		stringstream ss;
		vector<Stat*> res;

		//printf("[DEBUG] SELECT 拿到 %zu 行\n", res.size());
		fflush(stdout);

		Dict* dict = Dict::getInstance();
		Logger::getLogger()->logToFile("SelectStatement: About to call GetUser for " + username);
		User* user = dict->GetUser(username);
		Logger::getLogger()->logToFile("SelectStatement: GetUser returned");
		// 检查用户是否存在
		if (user == nullptr) {
			Logger::getLogger()->logToFile("SelectStatement: User is nullptr");
			return "Error: User '" + username + "' does not exist. Please check if the username is correct or contact administrator to create user.\n";
		}
		Logger::getLogger()->logToFile("SelectStatement: User found successfully");
		string _schema;

		if (fromTable->schema == nullptr)
			if (Dict::getCurSchema() != "")
				_schema = Dict::getCurSchema();
			else {
				delete user;
				return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
			}
		else
			_schema = fromTable->schema;
		Database* db = dict->GetDatabase(user, _schema);
		Class* cls = dict->GetClass(db, fromTable->name);
		if (cls == nullptr) {
			delete user;
			delete db;
			delete cls;
			return "Error: Unknown table '" + string(fromTable->name) + "'. Please check if the table name is correct or if the table has been created.\n";
		}
		vector<Attribute*> attrs = dict->GetAttribute(cls);

		// 已有代码：vector<Attribute*> attrs = ...;
		//9.11.3 语义分析
		for (Stat* proj : *selectList) {
			if (proj->type == kStatColumnRef) {
				if (!dict->findColumn(cls, attrs, proj->name)) {
					char buf[256];
					snprintf(buf, sizeof(buf),
						"Error: Column '%s' does not exist (line %d, column %d). Please check column name spelling or table structure",
						proj->name, proj->first_line, proj->first_column);
					return buf;
				}
			}
		}
		if (whereClause) {
			auto err = checkStatCols(whereClause, dict, cls, attrs);
			if (!err.empty()) return err;
		}

		//9.12.1
		/* 检查 WHERE 中所有“列 op 值”是否类型匹配 */
		auto typeErr = checkWhereColType(whereClause, dict, cls, attrs, whereLine, whereColumn);
		if (!typeErr.empty()) return typeErr;

		//9.12.1
		if (whereClause && !isBooleanContext(whereClause)) {
			char buf[128];
			snprintf(buf, sizeof(buf),
				"Error: WHERE clause must be a boolean expression (line %d, column %d). Please check logical operators and comparison operations in condition expression",
				errorLine, errorColumn);
			return buf;
		}

		vector<Stat*> stats;
		vector<bool> visit;

		bool hasIdx = false;
		for (auto attr : attrs) {
			if (attr->IsPkey()) {
				hasIdx = true;
				vector<string> rids;
				if (whereClause != nullptr && whereClause->stat->name == attr->name) {
					COMPARE_OPERATOR cp;
					if (whereClause->opType == kOpEquals)
						cp = EQ;
					else if (whereClause->opType == kOpGreater)
						cp = BT;
					else if (whereClause->opType == kOpGreaterEq)
						cp = BE;
					else if (whereClause->opType == kOpLess)
						cp = LT;
					else if (whereClause->opType == kOpLessEq)
						cp = LE;
					rids = IdxMgr::getInstance()->getRowids(attr->oid, whereClause->stat2, cp);
				}
				else {
					rids = IdxMgr::getInstance()->getRowids(attr->oid);
				}
				auto r = FileManager::getInstance()->multipleGet(rids);
				res.insert(res.begin(), r.begin(), r.end());
				break;
			}
		}
		if (!hasIdx) {
			Page* curblk = FileManager::getInstance()->getPage(cls->relfileid, cls->relblockid);
			do {
				auto r = curblk->getFromFrontToEnd();
				res.insert(res.begin(), r.begin(), r.end());
				curblk = FileManager::getInstance()->getPage(cls->relfileid, curblk->getNextPageid());
			} while (curblk->getNextPageid() == "");
		}

		res = select(res, whereClause, attrs);
		res = project(res, *selectList, attrs);

		//display

		//if ((*selectList)[0]->type == kStatStar) {
		//	for (auto attr : attrs) {
		//		ss << attr->name << "\t";
		//	}
		//	ss << endl;
		//}
		//else {
		//	for (auto item : (*selectList)) {
		//		ss << item->name << "\t";
		//	}
		//	ss << endl;
		//}
		//for (auto r : res) {
		//	for (auto item : (*r->statList)) {
		//		if (item->type == kStatLiteralInt)
		//			ss << item->ival << "\t";
		//		else if (item->type == kStatLiteralFloat)
		//			ss << item->fval << "\t";
		//		else if (item->type == kStatLiteralString)
		//			ss << item->name << "\t";
		//		else if (item->type == kStatLiteralNull)
		//			ss << "NULL" << '\t';    
		//	}
		//	ss << endl;
		//}


		//9.15
			// 修改输出格式
		if ((*selectList)[0]->type == kStatStar) {
			
			// 表头
			for (auto attr : attrs) {
				ss << "| " << setw(15) << left << attr->name << " ";
			}
			ss << "|" << endl;

			// 分隔线
			for (size_t i = 0; i < attrs.size(); i++) {
				ss << "+" << string(17, '-');
			}
			ss << "+" << endl;
		}
		else {
			// 表头
			for (auto item : (*selectList)) {
				ss << "| " << setw(15) << left << item->name << " ";
			}
			ss << "|" << endl;

			// 分隔线
			for (size_t i = 0; i < selectList->size(); i++) {
				ss << "+" << string(17, '-');
			}
			ss << "+" << endl;
		}

		int rowCount = 0;
		for (auto r : res) {
			rowCount++;
			for (auto item : (*r->statList)) {
				if (item->type == kStatLiteralBool) {
					//printf("[DEBUG] Found bool type, ival=%lld\n", item->ival);  // 调试打印
					ss << "| " << setw(15) << left << (item->ival ? "true" : "false") << " ";
				}
					
				else if (item->type == kStatLiteralInt)
					ss << "| " << setw(15) << left << item->ival << " ";
				else if (item->type == kStatLiteralFloat)
					ss << "| " << setw(15) << left << fixed << setprecision(2) << item->fval << " ";
				else if (item->type == kStatLiteralString)
					ss << "| " << setw(15) << left << (item->name ? item->name : "NULL") << " ";
				else if (item->type == kStatLiteralString)
					ss << "| " << setw(15) << left << (item->name ? item->name : "NULL") << " ";
				else if (item->type == kStatLiteralNull)
					ss << "| " << setw(15) << left << "NULL" << " ";

			}
			ss << "|" << endl;
		}

		// 底部统计信息
		ss << rowCount << " row" << (rowCount != 1 ? "s" : "") << " in set" << endl;
		delete user;
		delete db;
		delete cls;
		for (auto attr : attrs) {
			delete attr;
		}
		return ss.str();
	}



	// OrderDescription
	OrderDescription::OrderDescription(OrderType type, Stat* stat) :
		type(type),
		stat(stat) {
	}

	OrderDescription::~OrderDescription() {
		delete stat;
	}

	// LimitDescription
	LimitDescription::LimitDescription(int64_t limit, int64_t offset) :
		limit(limit >= 0 ? limit : kNoLimit),
		offset(offset > 0 ? offset : kNoOffset) {
	}

	// GroypByDescription
	GroupByDescription::GroupByDescription() :
		columns(nullptr),
		having(nullptr) {
	}

	GroupByDescription::~GroupByDescription() {
		delete having;

		if (columns != nullptr) {
			for (Stat* stat : *columns) {
				delete stat;
			}
			delete columns;
		}
	}

	//===============Select算子===================
	std::vector<Stat*> select(std::vector<Stat*> ori, Stat* whereClause, std::vector<Attribute*> attrs)
	{
		vector<Stat*> res;
		if (whereClause == nullptr)
			return ori;
		else {
			if (whereClause->isBoolLiteral && whereClause->ival == 1) {
				return ori;
			}
			else if (whereClause->opType == kOpAnd) {
				return intersectStats(select(ori, whereClause->stat, attrs), select(ori, whereClause->stat, attrs));
			}
			else if (whereClause->opType == kOpOr) {
				return unionStats(select(ori, whereClause->stat, attrs), select(ori, whereClause->stat2, attrs));
			}
			else {
				Stat* tableref = whereClause->stat;
				int idx = -1;
				for (int i = 0; i < attrs.size(); i++) {
					if (tableref->name == attrs[i]->name) {
						idx = i;
					}
				}
				if (idx == -1) {
					return res;
				}
				for (auto item : ori) {
					if (Stat::compare((*item->statList)[idx], whereClause->stat2, whereClause->opType)) {
						res.push_back(item);
					}
				}
			}
		}
		
		return res;
	}
	//===============Project算子===================
	std::vector<Stat*> project(std::vector<Stat*> ori, std::vector<Stat*> selectList, std::vector<Attribute*> attrs)
	{
		vector<Stat*> res;
		if (selectList.size() == 1 && selectList[0]->type == kStatStar)
			return ori;
		else {
			vector<bool> show;
			for (auto item : attrs) {
				bool found = false;
				for (auto s : selectList) {
					if (s->name == item->name)
					{
						found = true;
						break;
					}
				}
				show.push_back(found);
			}
			for (auto item : ori) {
				vector<Stat*>* tmp = new vector<Stat*>;
				for (int i = 0; i < show.size(); i++) {
					if (show[i])
						tmp->push_back((*item->statList)[i]);
				}
				res.push_back(Stat::makeArray(tmp));
			}
		}
		return res;
	}

	std::vector<Stat*> intersectStats(std::vector<Stat*> left, std::vector<Stat*> right)
	{
		vector<Stat*> res;
		for (int i = 0; i < left.size(); i++) {
			bool found = false;
			for (int j = 0; j < right.size(); j++) {
				if (left[i] == right[j])
					found = true;
			}
			if (found) {
				res.push_back(left[i]);
			}
		}
		return res;
	}

	std::vector<Stat*> unionStats(std::vector<Stat*> left, std::vector<Stat*> right)
	{
		vector<Stat*> res;
		res.insert(res.end(), right.begin(), right.end());
		for (int i = 0; i < left.size(); i++) {
			bool found = false;
			for (int j = 0; j < right.size(); j++) {
				if (left[i] == right[j])
					found = true;
			}
			if (!found) {
				res.push_back(left[i]);
			}
		}
		return res;
	}




	//===============Update算子===================
	UpdateStatement::UpdateStatement() :
		SQLStatement(ForUpdate),
		table(nullptr),
		updates(nullptr),
		where(nullptr) {
	}

	UpdateStatement::~UpdateStatement() {
		delete table;
		delete where;

		if (updates != nullptr) {
			for (UpdateClause* update : *updates) {
				free(update->column);
				delete update->value;
				delete update;
			}
			delete updates;
		}
	}

	string UpdateStatement::execute(string username)
	{
		stringstream ss;
		Dict* dict = Dict::getInstance();
		User* user = dict->GetUser(username);
		if (user == nullptr) {
			return "Error: User '" + username + "' does not exist or has no access permission.\n";
		}
		string _schema;
		if (table->schema == nullptr)
			if (Dict::getCurSchema() != "")
				_schema = Dict::getCurSchema();
			else {
				delete user;
				return "Error: No database selected. Please use USE statement to select a database first, e.g.: USE database_name;\n";
			}
		else
			_schema = table->schema;
		Database* db = dict->GetDatabase(user, _schema);
		Class* cls = dict->GetClass(db, table->name);
		if (cls == nullptr) {
			delete user;
			delete db;
			delete cls;
			return "Error: Unknown table '" + string(table->name) + "'. Please check if the table name is correct or if the table has been created.\n";
		}
		vector<Attribute*> attrs = dict->GetAttribute(cls);

		//9.11 语义分析
		//9.11.4
				/* ===== 列存在性检查 ===== */
		// 1. 检查 SET 左侧列
		for (auto* upd : *updates) {
			if (!dict->findColumn(cls, attrs, upd->column)) {
				char buf[256];
				/*snprintf(buf, sizeof(buf),
					"Error: Column '%s' does not exist (line %d, column %d). Please check column name spelling or table structure",
					upd->column, errorLine, errorColumn);*/
				snprintf(buf, sizeof(buf),
					"Error: Column '%s' does not exist (line %d, column %d). Please check column name spelling or table structure",
					upd->column,
					upd->columnLine,
					upd->columnCol);
				return buf;
			}
		}
		// 9-12 新增：SET 值类型一致性检查
		for (auto* upd : *updates) {
			Attribute* attr = dict->findColumn(cls, attrs, upd->column);
			if (!attr) continue;   // 前面已报过不存在，这里跳过
			string err = checkStatType(attr->type, upd->value, upd->column,
				errorLine, errorColumn);
			if (!err.empty()) return err;
		}
		// 2. 检查 WHERE 条件列
		if (where) {
			auto err = checkStatCols(where, dict, cls, attrs);
			if (!err.empty()) return err;
		}

		/* ---------- 检查 WHERE 中所有“列 op 值”是否类型匹配 ---------- */
		auto typeErr = checkWhereColType(where, dict, cls, attrs, whereLine, whereColumn);
		if (!typeErr.empty()) return typeErr;

		/* 检查 WHERE 是否为布尔上下文 */
		if (where && !isBooleanContext(where)) {
			char buf[128];
			snprintf(buf, sizeof(buf),
				"Error: WHERE clause must be a boolean expression, not a literal (line %d, column %d). Please use comparison or logical operators.",
				whereLine, whereColumn);
			return buf;
		}

		vector<bool> haveIdx;
		bool flag = false;
		for (auto b : haveIdx) {
			if (b == true) {
				flag = true;
			}
		}
		if (!flag) {
			// 9.12.1
			bool needIdx = false;
			Attribute* pkeyAttr = nullptr;  // 用于存储主键属性

			if (where != nullptr && where->opType == kOpEquals && where->stat != nullptr
				&& where->stat->type == kStatColumnRef) {
				// WHERE 主键等值 → 检查是否有索引
				for (auto attr : attrs) {
					if (attr->IsPkey() && attr->name == where->stat->name) {
						needIdx = true;
						pkeyAttr = attr;  // 保存主键属性
						break;
					}
				}
			}


			if (needIdx && !flag) {
				//char buf[256];
				//const char* col = where->stat->name;                 // 主键列名
				//const char* exp = statTypeName(pkeyAttr->type);      // 预期类型
				//const char* got = statTypeName(where->stat2->type);  // 实际类型
				//snprintf(buf, sizeof(buf),
				//	"Error: No index on primary key for equality filter (line %d, column %d): "
				//	"column '%s' expected %s, got %s",
				//	eqOpLine, eqOpColumn, col, exp, got);
				//delete user; delete db; delete cls;
				//for (auto attr : attrs) delete attr;
				//return buf;

				//9.13.3 bug修复
				// 检查实际类型是否真的不匹配
				bool typeMismatch = false;
				if (pkeyAttr && where->stat2) {
					// 检查类型是否真的不匹配
					if (pkeyAttr->type == kStatLiteralInt &&
						(where->stat2->type == kStatLiteralInt || where->stat2->type == kStatLiteralFloat)) {
						// INT 可以接受 INT 或 FLOAT（自动转换）
						typeMismatch = false;
					}
					else if (pkeyAttr->type == kStatLiteralFloat &&
						where->stat2->type == kStatLiteralInt) {
						// FLOAT 可以接受 INT（自动转换）
						typeMismatch = false;
					}
					else {
						typeMismatch = (pkeyAttr->type != where->stat2->type);
					}
				}

				if (typeMismatch) {
					char buf[256];
					const char* col = where->stat->name;
					const char* exp = statTypeName(pkeyAttr->type);
					const char* got = statTypeName(where->stat2->type);
					snprintf(buf, sizeof(buf),
						"Error: Primary key equality filter missing index (line %d, column %d): "
					"Column '%s' expects type %s, but got %s. Please check data type matching or create appropriate index",
						eqOpLine, eqOpColumn, col, exp, got);
					delete user; delete db; delete cls;
					for (auto attr : attrs) delete attr;
					return buf;
				}
				else {
					// 类型匹配，但仍然没有索引，给出更合适的错误信息
					char buf[256];
					const char* col = where->stat->name;
					snprintf(buf, sizeof(buf),
						"Warning: No index on primary key column '%s' (line %d, column %d). "
						"This may impact performance for equality filters.",
						col, eqOpLine, eqOpColumn);
					// 只是警告，不返回错误，继续执行
				}
			}


		}

		vector<Stat*> stats;
		vector<bool> visit;

		vector<string> rids;
		vector<Stat*> records;
		map<Stat*, string> recordRidMap;


		for (int i = 0; i < attrs.size(); i++) {
			bool hasIdx = false;
			if (attrs[i]->IsPkey()) {
				hasIdx = true;
				if (where != nullptr && where->type != kStatLiteralInt && where->stat->name == attrs[i]->name) {
					COMPARE_OPERATOR cp;
					if (where->opType == kOpEquals)
						cp = EQ;
					else if (where->opType == kOpGreater)
						cp = BT;
					else if (where->opType == kOpGreaterEq)
						cp = BE;
					else if (where->opType == kOpLess)
						cp = LT;
					else if (where->opType == kOpLessEq)
						cp = LE;
					rids = IdxMgr::getInstance()->getRowids(attrs[i]->oid, where->stat2, cp);
				}
				else {
					rids = IdxMgr::getInstance()->getRowids(attrs[i]->oid);
				}
				records = FileManager::getInstance()->multipleGet(rids);
				for (int i = 0; i < rids.size(); i++) {
					recordRidMap[records[i]] = rids[i];
				}
			}
			haveIdx.push_back(hasIdx);
		}


		vector<Stat*>res = select(records, where, attrs);
		vector<Stat*>tmp;
		vector<string> tobeUpdated;
		for (auto r : res) {
			tobeUpdated.push_back(recordRidMap[r]);
		}
		for (auto item : *updates) {
			if (item->value->type != kStatColumnRef) {
				int idx = -1;
				for (int i = 0; i < attrs.size(); i++) {
					if (attrs[i]->name == item->column) {
						idx = i;
						break;
					}
				}
				if (idx == -1) {
					delete user;
					delete db;
					delete cls;
					for (auto attr : attrs) {
						delete attr;
					}
					return "Error: Column named '" + string(item->column) + "' does not exist. Please check if the column name is correct or view table structure.\n";
				}
				else {
					for (auto i : res) {
						vector<Stat*>* s = new vector<Stat*>;
						for (int j = 0; j < (*i->statList).size(); j++) {
							if (j != idx) {
								s->push_back((*i->statList)[j]);
							}
							else {
								s->push_back(item->value);
							}
						}
						tmp.push_back(Stat::makeArray(s));
					}
				}
			}
			else {
				int idx1 = -1;
				for (int i = 0; i < attrs.size(); i++) {
					if (attrs[i]->name == item->column) {
						idx1 = i;
						break;
					}
				}
				int idx2 = -1;
				for (int i = 0; i < attrs.size(); i++) {
					if (attrs[i]->name == item->value->name) {
						idx2 = i;
						break;
					}
				}
				if (idx1 == -1 || idx2 == -1) {
					delete user;
					delete db;
					delete cls;
					for (auto attr : attrs) {
						delete attr;
					}
					return "Error: Column named '" + string(item->column) + "' does not exist. Please check if the column name is correct or view table structure.\n";
				}
				else {
					for (auto i : res) {
						vector<Stat*>* s = new vector<Stat*>;
						for (int j = 0; j < (*i->statList).size(); j++) {
							if (j != idx1) {
								s->push_back((*i->statList)[j]);
							}
							else {
								s->push_back((*i->statList)[idx2]);
							}
						}
						tmp.push_back(Stat::makeArray(s));
					}
				}
			}
		}
		FileManager::getInstance()->multipleUpdate(tobeUpdated, tmp);


		//9.15
		int affectedRows = 0;
		affectedRows = tobeUpdated.size();
		stringstream sss;
		sss << "Query successful, " << affectedRows << " rows affected" << endl;
		sss << "Rows matched: " << tobeUpdated.size() << ", Changed: " << affectedRows << endl;
		

		Logger::getLogger()->logToFile("Update " + string(_schema) + "." + string(table->name));
		delete user;
		delete db;
		delete cls;
		for (auto attr : attrs) {
			delete attr;
		}

		return sss.str();
	}

	// PrepareStatement
	PrepareStatement::PrepareStatement() :
		SQLStatement(ForPrepare),
		name(nullptr),
		query(nullptr) {
	}

	PrepareStatement::~PrepareStatement() {
		free(name);
		free(query);
	}
	string PrepareStatement::execute(string username)
	{
		return "";
	}

	// Alias
	Alias::Alias(char* name, std::vector<char*>* columns) :
		name(name),
		columns(columns) {
	}

	Alias::~Alias() {
		free(name);
		if (columns) {
			for (char* column : *columns) {
				free(column);
			}
			delete columns;
		}
	}

	// TableRef
	TableRef::TableRef(TableRefType type) :
		type(type),
		schema(nullptr),
		name(nullptr),
		alias(nullptr),
		select(nullptr),
		list(nullptr),
		join(nullptr) {
	}

	TableRef::~TableRef() {
		free(schema);
		free(name);

		delete select;
		delete join;
		delete alias;

		if (list != nullptr) {
			for (TableRef* table : *list) {
				delete table;
			}
			delete list;
		}
	}

	bool TableRef::hasSchema() const {
		return schema != nullptr;
	}

	const char* TableRef::getName() const {
		if (alias) return alias->name;
		else return name;
	}

	// JoinDefinition
	JoinDefinition::JoinDefinition() :
		left(nullptr),
		right(nullptr),
		condition(nullptr),
		type(kJoinInner) {
	}

	JoinDefinition::~JoinDefinition() {
		delete left;
		delete right;
		delete condition;
	}

	ment::UseStatement::UseStatement() :
		SQLStatement(ForUse)
	{
	}
	string ment::UseStatement::execute(string username)
	{
		auto dict = Dict::getInstance();
		Logger::getLogger()->logToFile("UseStatement: About to call GetUser for " + username);
		auto user = dict->GetUser(username);
		Logger::getLogger()->logToFile("UseStatement: GetUser returned");
		if (user == nullptr) {
			Logger::getLogger()->logToFile("UseStatement: User is nullptr");
			return "Error: User does not exist. Please check if the username is correct or contact administrator to create user.\n";
		}
		Logger::getLogger()->logToFile("UseStatement: User found successfully");
		auto db = dict->GetDatabase(user, schema);
		if (db != nullptr) {
			Dict::setCurSchema(schema);
			Logger::getLogger()->logToFile("Change default database to " + string(schema));
			delete user;
			delete db;
			return "Database switched\n";
		}
		else {
			delete user;
			return "Error: Unknown database '" + string(schema) + "'. Please check if the database name is correct or contact administrator to create database.\n";
		}
	}


	std::string checkStatCols(Stat* e, Dict* dict, Class* cls, const std::vector<Attribute*>& attrs) {
		if (!e) return "";

		switch (e->type) {
		case kStatColumnRef:               // 列名
			if (!dict->findColumn(cls, attrs, e->name)) {
				return "Error: Column '" + std::string(e->name) + "' does not exist. (line: " + std::to_string(e->first_line) + ", column: " + std::to_string(e->first_column) + "). Please check if the column name is correct or view table structure.";
			}
			return "";
		case kStatOperator:                // 二元/多元运算
			// 左子树
			if (e->stat) {
				auto left = checkStatCols(e->stat, dict, cls, attrs);
				if (!left.empty()) return left;
			}
			// 右子树
			if (e->stat2) {
				auto right = checkStatCols(e->stat2, dict, cls, attrs);
				if (!right.empty()) return right;
			}
			// 子表达式列表（IN、BETWEEN 等）
			if (e->statList) {
				for (auto* child : *e->statList) {
					auto err = checkStatCols(child, dict, cls, attrs);
					if (!err.empty()) return err;
				}
			}
			return "";
		default:                           // 字面量、函数等跳过
			return "";
		}
	}

	//9.12 类型判断
	// 类型检查函数定义
	static string checkStatType(StatType statType, Stat* val, const char* colName, int line, int column) {
		if (!val) return "";
		if (val->type == kStatLiteralNull) return "";  // NULL 是合法的所有类型

		bool ok = false;
		switch (statType) {
		case kStatLiteralInt:
			ok = (val->type == kStatLiteralInt);
			break;
		case kStatLiteralFloat:
			ok = (val->type == kStatLiteralFloat || val->type == kStatLiteralInt);
			break;
		case kStatLiteralString:
			ok = (val->type == kStatLiteralString);
			break;
		case kStatLiteralBool:
			ok = (val->type == kStatLiteralBool);
			break;
		default:
			break;
		}

		//if (!ok) {
		//	char buf[256];
		//	snprintf(buf, sizeof(buf),
		//		"Error: column '%s' type mismatch (line %d, column %d)",
		//		colName, line, column);
		//	return buf;
		//}
		//return "";

		//9.12 类型检查
		if (!ok) {
			char buf[512];
			snprintf(buf, sizeof(buf),
				"Error: Column '%s' type mismatch (line %d, column %d): expected type %s, but got %s. Please check if the data type is correct.",
				colName, line, column,
				statTypeName(statType),
				statTypeName(val->type));
			return buf;
		}
		return "";
	}
} // namespace ment
